<?php

namespace App\Console\Commands;

use App\Enums\OrderStatus;
use App\Models\ProductConfig;
use Carbon\Carbon;
use Illuminate\Console\Command;

class ResaleBasePriceCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'resale:calc_avg_price';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '计算前一天转售基准价';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //查询前一天所有转售商品的平均成交价格
        $list = \DB::table('orders')
            ->join('products', 'orders.product_id', '=', 'products.id')
            ->where('is_resale', 1)
            ->where('order_status', OrderStatus::PAID)
            ->whereDate('orders.created_at', Carbon::yesterday()->toDateString())
            ->select(['contract_address', \DB::raw('avg(quantity*sale_price) as avg_price')])
            ->groupBy(['contract_address'])
            ->get();
        foreach ($list as $item) {
            $price = toYuan($item->avg_price);
            ProductConfig::set($item->contract_address, ProductConfig::RESALE_BASE_PRICE, $price);
            $this->output->writeln(sprintf('[%s] set resale_bases_price to : %s', $item->contract_address, $price));
        }

        return 0;
    }
}
